
var npm_repo = require("./npm_repo.js");
var sqlite3 = require(npm_repo("sqlite3")).verbose();

var db = {
	file: null,
	handle: null
};

db.init = function(file){
	return new Promise(function(resolve, reject){
		if (null === db.handle)
		{
			db.handle = new sqlite3.Database(file, sqlite3.OPEN_READWRITE, function(error){
				if (error)
				{
					reject(error);
				}
				else
				{
					db.file = file;
					resolve();
				}
			});
		}
		else
		{
			resolve();
		}
	});
};

db.query = function(sql){
	return new Promise(function(resolve, reject) {
		db.handle.all(sql, function(err, rows) {
			if (err)
			{
				reject(err);
			}
			else
			{
				resolve(rows);
			}
		});
	});
};

db.exec = function(sqls){
	db.handle.serialize(function(){
		for (let sql of sqls)
		{
			db.handle.run(sql);
		}
	}, function(err){
		console.error("db.exec(%s) failed, error: %s", util.inspect(arguments), JSON.stringify(err));
	});
}

module.exports = db;